package com.ruoyi.system.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator {

    // 生成包含用户ID的二维码
    public static void generateUserIDQRCode(String msg, String filePath, int width, int height) throws Exception {
        // 创建二维码内容
        String qrCodeData = msg; // 这里可以根据需要修改二维码内容

        // 设置二维码参数，去除白边
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.MARGIN, 1); // 设置边距为0，去除白边

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeData, BarcodeFormat.QR_CODE, width, height, hints);

        // 创建BufferedImage对象
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 填充矩阵数据到图像
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        // 确保目录存在
        File outputFile = new File(filePath);
        if (!outputFile.exists()) {
            outputFile.mkdirs(); // 创建所有必要的父目录
        }

        // 确保文件路径指向具体文件而不是目录
        if (outputFile.isDirectory()) {
            outputFile = new File(outputFile, msg + ".png");
        }

        // 输出到文件
        ImageIO.write(bufferedImage, "png", outputFile);
    }

    // 新增方法：生成更大尺寸且无白边的二维码
    public static void generateLargeQRCodeWithoutMargin(String msg, String filePath, int size) throws Exception {
        generateUserIDQRCode(msg, filePath, size, size);
    }

}
